// pages/login/login.ts
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from "~/stores/app"
import config from '~/config/index'
import { doRegister } from '~/api/user'
import { back } from '@utils/util'
let loading: boolean = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkboxValue: [] as string[],
    setting: config
  },
  checkChange(event: any) {
    this.setData({
      checkboxValue: event.detail.value
    })
  },
  handCheckChange() {
    const checkboxValue = this.data.checkboxValue.length === 1 ? [] : ['ok']
    this.setData({
      checkboxValue: checkboxValue
    })
  },
  getCode() {
    return new Promise((resolve) => {
      wx.login({
        success(e) {
          resolve(e.code)
        }
      })
    })
  },
  async getPhoneNumber(this: any, e: any) {
    if (loading) return
    loading = true
    try {
      await this.doUserInfo()
      back()
    } catch {
      this.handRegister(e.detail.code)
      loading = false
    }
  },
  async handRegister(this: any, phoneCode: string) {
    try {
      const staticCode = await this.getCode()
      await doRegister({
        phoneCode,
        staticCode
      })
      await this.doUserInfo()
      loading = false
      back()
    } catch (error) {
      loading = false
    }
  },
  handJump(url: string) {
    wx.navigateTo({
      url
    })
  },
  onBack() {
    back()
  },
  onGoHome() {
    wx.switchTab({
      url: '/pages/tabbar/home/index',
    });
  },
  handTips() {
    wx.showToast({
      icon: 'none',
      title: '请先认真阅读并同意《用户协议》及《隐私政策》'
    })
  },
  /**
 * 生命周期函数--监听页面加载
 */
  onLoad(this: any) {
    this.storeBinding = createStoreBindings(this, {
      store,
      actions: ['doUserInfo']
    });
  },
  /**
 * 生命周期函数--监听页面卸载
 */
  onUnload(this: any) {
    this.storeBinding.destroyStoreBindings();
  },
})